package com.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dao.CateGoryDao;
import com.dao.GoodsDao;
import com.dao.Impl.CateGoryDaoImp;
import com.dao.Impl.GoodsDaoImpl;
import com.dao.Impl.SupplieDaoImpl;
import com.dao.Impl.UnitDaoImpl;
import com.dao.UnitDao;
import com.entity.*;
import com.util.MyUtil;
import com.util.TransBean;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(value = "/goodsController/*")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String uri = request.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);
        String target = null;
        switch (method) {
            case "findId":
                findId(request, response);
                return;
            case "modify":
                modify(request, response);
                return;
            case "show":
                showPage(request, response);
                return;
            case "showIni":
                target = showIni(request, response);
                break;
            case "add":
                target = add(request, response);
                break;
            case "showAdd":
                target = showAdd(request, response);
                break;
            case "findName":
                target = findName(request, response);
                break;
            case "search":
                search(request, response);
                break;
            case "findGoodsStock":
                target=findGoodsStock(request, response);
                break;
            case "updateNumstatus":
                target=updateNumstatus(request, response);
                break;
            default:
                break;
        }
        if (target != null) {
            request.getRequestDispatcher(target).forward(request, response);
        }
    }

    private String updateNumstatus(HttpServletRequest request, HttpServletResponse response) {
        int goodsId= Integer.parseInt(request.getParameter("goodsId"));
        GoodsDao dao=new GoodsDaoImpl();
        int i = dao.alterNumstatus(goodsId);
        MyUtil.jsonWriter(response,i);
        return null;
    }


    /**
     * 库存信息分页查询
     * @param request
     * @param response
     * @return
     */
    private String findGoodsStock(HttpServletRequest request, HttpServletResponse response) {
        PageBean<Map> page=new PageBean<>();
        TransBean.populate(page,request.getParameterMap());
        GoodsDao dao=new GoodsDaoImpl();
        dao.findGoods(page);
        MyUtil.jsonWriter(response,page);
        return null;
    }


    /**
     * 查找商品名称
     * @param request
     * @param response
     * @return
     */
    private String findName(HttpServletRequest request, HttpServletResponse response) {
        GoodsDao dao=new GoodsDaoImpl();
        List<Map> name = dao.findName();
        MyUtil.jsonWriter(response,name);
        return null;
    }


    private void search(HttpServletRequest request, HttpServletResponse response) {
        String goodsName = request.getParameter("goodsName");
        MyUtil.jsonWriter(response,new GoodsDaoImpl().search(goodsName));
    }

    /**
     * 分页多表联查（ajax）
     * @param request
     * @param response
     * @return
     */
    private String showPage(HttpServletRequest request, HttpServletResponse response) {
        PageBean pageBean = new PageBean();
        TransBean.populate(pageBean, request.getParameterMap());
        GoodsDao dao = new GoodsDaoImpl();
        UnitDao dao1 = new UnitDaoImpl();
        List<Unit> unitList = dao1.findAll();
        dao.findSctn(pageBean);
        JoinQuery join = new JoinQuery(unitList, pageBean);
        MyUtil.jsonWriter(response, join);
        return null;
    }

    /**
     * 从此处进入商品管理显示商品单位和商品类别
     * @param request
     * @param response
     * @return
     */
    private String showIni(HttpServletRequest request, HttpServletResponse response) {
        UnitDao unitDao = new UnitDaoImpl();
        CateGoryDao cateGoryDao = new CateGoryDaoImp();

        List<Unit> unitList = unitDao.findAll();
        List<Category> categoryList = cateGoryDao.findAll();

        request.setAttribute("unitList", unitList);
        request.setAttribute("cgs", categoryList);
        return "/shop/shopManage.jsp";
    }

    /**
     * 根据id查询数据传回前端（ajax）
     * @param request
     * @param response
     * @return
     */
    private String findId(HttpServletRequest request, HttpServletResponse response) {
        GoodsDao dao = new GoodsDaoImpl();
        Integer goodsId = Integer.valueOf(request.getParameter("goodsId"));
        Goods goods = dao.findById(goodsId - 1000);
        String s = JSONArray.toJSONString(goods);
        try {
            response.getWriter().println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改商品信息（ajax）
     * @param request
     * @param response
     * @return
     */
    private String modify(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        Map<String, String[]> map = request.getParameterMap();
        Goods goods = new Goods();
        try {
            BeanUtils.populate(goods, map);
            out = response.getWriter();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        GoodsDaoImpl dao = new GoodsDaoImpl();

        if (goods.getName() != null) {
            int i = dao.modify(goods);
            if (i != -1) {
                out.println(JSON.toJSONString(goods));
            } else {
                out.println(-1);
            }
        } else {
            dao.modifyStatus(goods);
            out.println(JSON.toJSONString(goods.getStatus()));
        }
        return null;
    }

    /**
     * 增加商品
     * 请求转发会重复提交表单数据
     * 所以用了重定向
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    private String add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Goods goods = new Goods();
        GoodsDao dao = new GoodsDaoImpl();
        TransBean.populate(goods, request.getParameterMap());
        int i = dao.addGoods(goods);
        MyUtil.jsonWriter(response, i);

        return null;
    }

    /**
     * 从此处进入商品增加有单位和类别的下拉框
     * @param request
     * @param response
     * @return
     */
    private String showAdd(HttpServletRequest request, HttpServletResponse response) {
        UnitDao unitDao = new UnitDaoImpl();
        CateGoryDao cateGoryDao = new CateGoryDaoImp();
        GoodsDao goodsDao = new GoodsDaoImpl();
        Integer goodsId = goodsDao.selectMaxId();
        List<Unit> unitList = unitDao.findAll();
        List<Category> categoryList = cateGoryDao.findAll();
        List<Supplie> supp = new SupplieDaoImpl().findAll();

        Map map = new HashMap();
        map.put("supplies", supp);
        map.put("unitList", unitList);
        map.put("cgs", categoryList);
        map.put("goodsId", goodsId + 1001);

        MyUtil.jsonWriter(response, map);
        return null;
    }


}
